var textId;//文本框id
var oneOrMore; //是否可以多选 1 单选 2 多选
var dialogId; //模态框id
var limitOrg; //限制部门
var defaultOrg; //默认部门
var limitPosition; //限制身份
$(function () {   
	var treeId = 'orgTree';
	oneOrMore = GetQueryString("oneOrMore");
	textId = GetQueryString("textId");
	dialogId = GetQueryString("dialogId");
	limitOrg = GetQueryString("limitOrg");
	defaultOrg = GetQueryString("defaultOrg");
	limitPosition = GetQueryString("limitPosition");
	tagIni();
	if(defaultOrg==""||defaultOrg==null){
		defaultOrg = 'guanlingdao';
	}
	createOrgTree(treeId,defaultOrg,oneOrMore);
});

//选择的部门列表的文本
var textOrg = "";
//选择的部门列表的Id
var idOrg = "";
//选择的对象列表的文本
var textObject = "";
//选择的对象列表的Id
var idObject = "";
//部门标签数目
var count = 0;
//人员/库房标签的数目
var tagsNum = 0;

//************************************选择部门************************************


/*点击“添加”图标后将选择的部门添加到文本框中
 * oneChoiceDom:只能单选的字段
 * treeId:机构树ID
 */
function getSelectedOrg(oneChoiceDom,treeId,dialogId){
    var treeObj = $.fn.zTree.getZTreeObj(treeId);
	var node = treeObj.getSelectedNodes();
	if (node){
		var s = node[0].name;
		var id = node[0].id;
		count++;
		if(textId==oneChoiceDom && count==1){
			//把选中的部门转化成标签
			if(!$('#selectedOrg').tagExist(s))
				$('#selectedOrg').addTag(s);
			else{
				alertFunc("请不要重复选择！");
			}
			$("#selectedOrg").attr("orgIds",id);
			$("#selectedOrg").attr("text",s);
		}else if(textId=="tiYongBuMen" && count>1){
			alertFunc("只能选择一个部门");
		}else{
			//把选中的部门转化成标签
			if(!$('#selectedOrg').tagExist(s)){
				$('#selectedOrg').addTag(s);
				textOrg += s + ',';
				idOrg += id + ',';
			}
			else{
				alertFunc("请不要重复选择！");
			}
			$("#selectedOrg").attr("text",textOrg);
			$("#selectedOrg").attr("orgIds",idOrg);
		}			
	}
	//从树上取消选中节点
	treeObj.cancelSelectedNode(node[0]);
}

//点击“确定”后把对话框中选到的部门添加到主页面的部门文本框中，并关闭对话框
function setSelectedOrg(){
	var text = $("#selectedOrg").attr("text");
	var orgIds = $("#selectedOrg").attr("orgIds");
	$("#" + textId + "Text").val(text);
	$("#" + textId).val(orgIds);
	//判断元素是否为必填
	if(typeof($("#" + textId + "Text").attr("data-status"))!="undefined" && text !=""){
		$("#" + textId + "Text").attr("data-status","1");
	}
	$("#"+dialogId).modal("hide");
}

////判断选择部门窗口是否关闭，如果为关闭状态，则清空数据
//function isClosedOrg(treeId,dialogId){
//	$("#"+dialogId).on('hidden.bs.modal',function(){
//		var treeObj = $.fn.zTree.getZTreeObj(treeId);
//    	var node = treeObj.getSelectedNodes();
//    	treeObj.cancelSelectedNode(node[0]);
//		textOrg = "";
//		idOrg = "";
//		$("#selectedOrg").attr("text",textOrg);
//		$("#selectedOrg").attr("orgIds",idOrg);
//		$("#searchOrg").attr("value","");
//		//清空input中的标签
//		$('#selectedOrg').importTags('');
//		//将用户选中的合同主办部门数重置为0
//		count = 0;
//	})
//}

//************************************选择人员/库房************************************

//点击“确定”后把对话框中选到的对象添加到主页面的文本框中，并关闭对话框
function setSelectedObject(){
	var text = $("#selectedObject").attr("text");
	var ids = $("#selectedObject").attr("idObject");
//	var orgId= $("#selectedObject").attr("orgId");
	if(text!=undefined){		
		text = text.substr(0,text.length-1);
		ids = ids.substr(0,ids.length-1);	
	}else{
		text = "";
		ids="";
	}
	$("#" + textId + "Text",parent.document).val(text);
	$("#" + textId,parent.document).val(ids);
	//判断元素是否为必填
	if(typeof($("#" + textId + "Text",parent.document).attr("data-status"))!="undefined" && text !=""){
		$("#" + textId + "Text",parent.document).attr("data-status","1");
	}
	closeWin();
}

////清空数据
//function isClosedObject(treeId){
//	var treeObj = $.fn.zTree.getZTreeObj(treeId);
//	//取消选中的节点
//	var node = treeObj.getSelectedNodes();
//	treeObj.cancelSelectedNode(node[0]); 
//	textObject = "";
//	idObject = "";
//	$("#object").html("");
//	$("#selectedObject").attr("text",textObject);
//	$("#selectedObject").attr("idObject",idObject);
//	$("#searchObject").attr("value","");
//	tagsNum = 0;
//	//清空input中的标签
//	$('#selectedObject').importTags('');
//}


//初始化tag标签
function tagIni(){
	$("#selectedOrg").tagsInput({
		width: 250,
		height: 380,
		'defaultText':"",
		//删除标签时的回调函数
		'onRemoveTag':function(tag){
			var text = $("#selectedOrg").attr("text");
			var length = text.length;
			var lengthTag = tag.length;
			var n = text.indexOf(tag);
			var arr = text.split(",");
			text = text.substr(0,n) + text.substr(n+lengthTag+1,length);
			textOrg = text;
			$("#selectedOrg").attr("text",textOrg);
			
			var indexId = arr.indexOf(tag);
			var orgIds = $("#selectedOrg").attr("orgIds");
			var arrId = orgIds.split(",");
			orgIds="";
			for(var index=0;index<arrId.length-1;index++){
				if(index != indexId){
					orgIds += arrId[index] + ",";
				}
			}
			idOrg = orgIds;
			$("#selectedOrg").attr("orgIds",idOrg);
			count--;
		}
	});
	
	$("#selectedObject").tagsInput({
		width: 200,
		height: 380,
		'defaultText':"",
		//删除用户标签时的回调函数
		'onRemoveTag':function(tag){
			var text = $("#selectedObject").attr("text");
			var length = text.length;
			var lengthTag = tag.length;
			var n = text.indexOf(tag);
			var arr = text.split(",");
			text = text.substr(0,n) + text.substr(n+lengthTag+1,length);
			textObject = text;
			$("#selectedObject").attr("text",textObject);
			
			var indexId = arr.indexOf(tag);
			var objectIds = $("#selectedObject").attr("idObject");
			var arrId = objectIds.split(",");
			objectIds="";
			for(var index=0;index<arrId.length-1;index++){
				if(index != indexId){
					objectIds += arrId[index] + ",";
				}
			}
			idObject = objectIds;
			$("#selectedObject").attr("idObject",idObject);
			tagsNum--;
		},
		'onAddTag':function(tag){
			tagsNum++;
		}
	})
}

//关闭窗口
function closeWin(){
	$("#closeWin_btn",parent.document).click();
}

//获取用户机构树的url
var getOrgTreeUrl = ProjectName+"/root.getOrganization.do";
//获取机构内人员信息的url
var getUserUrl = ProjectName+"/root.getUserListByOrg.do?orgid=";
//获取机构内库房信息的url
var getKuFangUrl = '';

var key;
var lastValue = "", nodeList = [], fontCss = {}; 

 //结构树的初始化(单选)
var settingObject = {
    data: {
        simpleData: {
            enable: true
        }
    },
    callback: {
		onClick: zTreeOnClick
	}
};
//结构树的初始化(多选)
var settingObjectMore = {
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
    		onClick: zTreeOnClickMore
    	}
    };

/*
 * 构建机构树
 * getOrgTreeUrl:获取机构树数据的url
 * treeId:机构树ID
 * orgId:当前用户的所属部门
 * */
function createOrgTree (treeId,orgId,oneOrMore) {
	//var url = urlRoot + '/remote/user/getOrgTree.do';
	var url = getOrgTreeUrl;
    var zNodes;
    var treeObjectObj;
    $.ajax({
        url: url,
        type: 'get',
        cache:false,
        dataType: "json", //可以是text，如果用text，返回的结果为字符串；如果需要json格式的，可是设置为json
        success: function(data) {
            zNodes = data;
            $.fn.modal.Constructor.prototype.enforceFocus = function() {};
            if(zNodes.status == "ok"){
            	//$.fn.zTree.init($("#userTree"), settingUser, zNodes.rows);
            	//选择的对象为单选
            	var datas =new Array();
            	if(limitOrg!=""&&limitOrg!=null){
            		var limitorgarr = limitOrg.split(",");
            		$.each(zNodes.rows,function(index,rowdata){
            			if(rowdata.id=="shandongbowuguan"){
            				datas.push(rowdata);
            				return true;
            			}
            			$.each(limitorgarr,function(index,limitdata){
                			if(rowdata.id==limitdata){
                				datas.push(rowdata);
                			}
                		});
            		});
            	}else{
            		datas = zNodes.rows
            	}
            	if(oneOrMore==1){
            		$.fn.zTree.init($("#"+treeId), settingObject, datas);
            	}
            	else{
            		$.fn.zTree.init($("#"+treeId), settingObjectMore, datas);
            	}
                //search("userTree","searchUser");
                //treeuserObj = $.fn.zTree.getZTreeObj("userTree");
            	treeObjectObj = $.fn.zTree.getZTreeObj(treeId);
                //折叠所有节点
                treeObjectObj.expandAll(false);
                //打开根节点
                var root = treeObjectObj.getNodeByParam("id", "shandongbowuguan", null);
                treeObjectObj.expandNode(root);
                //定位到当前用户的所属部门
                var orgNodeObject = treeObjectObj.getNodeByParam("id",orgId,null);
                treeObjectObj.selectNode(orgNodeObject);
                treeObjectObj.expandNode(orgNodeObject,true,true,true);
                treeObjectObj.updateNode(orgNodeObject);
                //为选中的节点设置触发点击事件
                $(".curSelectedNode").trigger("click");
            }
        },
        error: function(msg) {
            alert("失败");
        }
    });
}

/*
 * 点击回调事件(单选)
 * treeId:结构树ID
 * treeNode:结构树上被点击的节点ID
 */	
function zTreeOnClick(event, treeId, treeNode) {
	var url = getUserUrl + treeNode.id;
	//var url = urlRoot + "/resources/json/objectInfo.json";
	$("#object").html("");
	$.ajax({
		type:"get",
		url:url,
        cache:false,
		dataType:"json",
		success:function(object){
			if(object.status == "ok"){
				$.each(object.rows,function(i,item){
					var objectP = document.createElement('p');
					var objectA = document.createElement('a');
					objectA.id = item.userid;
					objectA.href = "javascript:void(0)";
					objectA.innerText = item.username;
					
					objectA.onclick = function(){
						//把选中的对象转化成标签
						if($('#selectedObject').tagExist(item.username)){
							alertFunc("请不要重复选择！");
						}
						else{
							if(tagsNum==1){
								alertFunc("只能选择一项！");
							}
							else{
								$('#selectedObject').addTag(item.username);
								textObject += item.username + ",";
								idObject += item.userid + ",";
							}
						}
						$("#selectedObject").attr("text",textObject);
						$("#selectedObject").attr("idObject",idObject);
						$("#selectedObject").attr("orgId",treeNode.id);
					};
					$(objectP).append(objectA);
					$("#object").append(objectP);
				})	
			}
		}
	})
};

/*
 * 点击回调事件(多选)
 * treeId:结构树ID
 * treeNode:结构树上被点击的节点ID
 */	
function zTreeOnClickMore(event, treeId, treeNode) {
	var url = getUserUrl + treeNode.id;
	//var url = urlRoot + "/resources/json/objectInfo.json";
	$("#object").html("");
	$.ajax({
		type:"get",
		url:url,
        cache:false,
		dataType:"json",
		success:function(object){
			if(object.status == "ok"){
				$.each(object.rows,function(i,item){
					var objectP = document.createElement('p');
					var objectA = document.createElement('a');
					objectA.id = item.userid;
					objectA.href = "javascript:void(0)";
					objectA.innerText = item.username;
					
					objectA.onclick = function(){
						//把选中的对象转化成标签
						if($('#selectedObject').tagExist(item.username)){
							alertFunc("请不要重复选择！");
						}
						else{
							$('#selectedObject').addTag(item.username);
							textObject += item.username + ",";
							idObject += item.userid + ",";
						}
						$("#selectedObject").attr("text",textObject);
						$("#selectedObject").attr("idObject",idObject);
						$("#selectedObject").attr("orgId",treeNode.id);
					};
					$(objectP).append(objectA);
					$("#object").append(objectP);
				})	
			}
		}
	})
};

//搜索变色
function getFontCss(treeId, treeNode) {
      
        return (!!treeNode.highLight) ? { color: "#A60000", "font-weight": "bold" } : { color: "#333", "font-weight": "normal" };
}

function focusKey(e) {
    if (key.hasClass("empty")) {
        key.removeClass("empty");
    }
}
function blurKey(e) {
    if (key.get(0).value === "") {
        key.addClass("empty");
    }
}

//搜索节点，不使用模糊，使用全匹配，当然也可以使用节点ID，文字，模糊查询所有节点，也很简单，不做叙述，类似下面，只是调用方法不同
function searchNode(treeId) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        updateNodes(false,treeId);
        var value = $.trim(key.get(0).value);
        if (value != "") {
            var keyType = "name";
            nodeList = zTree.getNodesByParam(keyType, value);
            updateNodes(true,treeId);
        }
       
    }
//更新节点，使其高亮显示，加了展开节点，达到了定位的效果
function updateNodes(highLight,treeId) {
    var zTree = $.fn.zTree.getZTreeObj(treeId);
    for (var i = 0, l = nodeList.length; i < l; i++) {
        nodeList[i].highLight = highLight;
        //定位到节点并展开
        zTree.selectNode(nodeList[i]);
        zTree.expandNode(nodeList[i]);
        zTree.updateNode(nodeList[i]);
    }
}

//treeId为树的Id，searchText为搜索框的Id
function search(treeId,searchText){
	 key = $("#" + searchText);
     key.bind("focus", focusKey)
     .bind("blur", blurKey);
    
     $("#" + searchText).keydown(function (e) {
         if (e.keyCode == 13) {
             searchNode(treeId);
             e.keyCode = 0;
             window.event.keyCode = 0;
             e.preventDefault();
             return;
         }
     });
     $("#searchBtn").click(function () {
    	 searchNode(treeId);
     });
}